# -*- coding: utf-8 -*-
"""
Created on Tue Sep 14 14:15:30 2021

@author: chibi
"""

import cv2 
from PIL import Image

cap = cv2.VideoCapture('eva2-20s.mp4')

all_frames = cap.get(7)
fps = cap.get(5)
w = cap.get(3)
h = cap.get(4)
delaytime = int(1000/fps)
print(delaytime)

print("所有帧数：%d 当前帧率：%f , 视频宽度：%d , 视频高度:%d" %(all_frames ,fps,w,h))
import socket
esp_ip  = '192.168.88.100'
esp_port = 8888

serverAddressPort   = (esp_ip, esp_port)
bufferSize          = 1024
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

#UDPClientSocket.sendto(b"xxx", serverAddressPort)

def readframe(frames):
    dim = (128, 64)
  
    # resize image
    resized = cv2.resize(frames, dim, interpolation = cv2.INTER_AREA)
    im = Image.fromarray(cv2.cvtColor(resized,cv2.COLOR_BGR2RGB))
    #im.show()
    #im = im.convert("L")
    im = im.convert("1")
    text =''
    point = 0
    for y in range (64):
        for x in range (128):
            if im.getpixel((x,y)) <50:
                get_point = 0
            else:
                get_point = 1
                
            
            now = int( get_point )<<(3-x%4) 
            #位数1/0 转二进制
           
            point += now
            
            if (x%4 ==3):
                text += hex(point)[2:]
               
                #text += "|"
                point = 0 #还原
    text += "#"
    #print(text)
    
    UDPClientSocket.sendto(text.encode('utf-8'), serverAddressPort)
index_l = 0
while cap.isOpened():
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #resized = cv2.resize(frame, (w,h), interpolation = cv2.INTER_AREA)
    #resized = cv2.resize(frame, (int(w/2),int(h/2)), interpolation = cv2.INTER_AREA)
    #cv2.imshow('reside',resized)
    if index_l%4 ==3:
        readframe(frame)
    cv2.imshow('frame',frame)
    index_l += 1
    
    
    if cv2.waitKey(delaytime) == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()